import React, { useEffect, useState, Fragment } from 'react'
import { Button, Input, DatePicker, Table, message, Select, Tag } from 'antd'
import { connect } from 'react-redux'
import { withRouter } from 'react-router-dom'
import moment from 'moment'
import locale from 'antd/es/date-picker/locale/zh_CN'
import EditOrder from './EditOrder'
import { getChannelList, getAllProduct } from '../../../request/product'
import { createExport, getExportFile } from '../../../request/order'
import SetOrderStatus from './SetOrderStatus'
import 'moment/locale/zh-cn'
import { actionCreators } from '../store'
import OrderDetail from '../Detail'
import ENUMS, { ROLE_ADMIN, ROLE_CUSTOMER_SERVICE, ROLE_AGENT } from '../../../constants'
import '../style.scss'

moment.locale('zh-cn')

function OrderList(props) {
  const { getList, orderStatusMap, isAll, setCurrentPage, currentPage, loginUser } = props
  const [orderList, setOrderList] = useState([])
  const [page, setPage] = useState(1)
  const [totalCount, setTotalCount] = useState(0)
  const [isLoading, setIsLoading] = useState(false)
  const [isShowEdit, setIsShowEdit] = useState(false)
  const [isShowSetStatus, setIsShowSetStatus] = useState(false)
  const [editRow, setEditRow] = useState({})
  const [packageList, setPackageList] = useState([])
  const [productList, setProductList] = useState([])
  const [selectedRowKeys, setSelectRowKeys] = useState([])
  const [isExportBtnLoading, setIsExportBtnLoading] = useState(false)
  const [isShowOrderDetail, setIsShowOrderDetail] = useState(false)
  const [currentOrderNo, setCurrentOrderNo] = useState('')
  const [search, setSearch] = useState({
    createTime: [],
    deliverTime: [],
    activeTime: [],
    keyword: '',
    searchType: 'order_no',
    isp: 0,
    status: 0,
    partner_id: 0,
    partner_goods_code: []
  })
  const pageSize = 30
  let timeId = null

  useEffect(() => {
    getOrderList(currentPage).catch(e => console.log(e.message))
    getProductList().catch(e => console.log(e.message))

    if (loginUser.role_id !== ROLE_AGENT) {
      getAllChannel().catch(e => console.log(e.message))
    }

    return () => {
      if (timeId) {
        clearInterval(timeId)
      }
    }
  }, [])

  useEffect(() => {
    setSearch(search => ({ ...search, partner_goods_code: [] }))
    getProductList().catch(e => console.log(e.message))
  }, [search.partner_id])

  const getAllChannel = async() => {
    const res = await getChannelList()
    if (res.code) {
      message.error(res.message)
      return false
    }
    setPackageList(res.data)
  }

  const getProductList = async() => {
    const params = { partner_id: search.partner_id }
    if (!search.partner_id) {
      delete params.partner_id
    }
    const res = await getAllProduct(params)
    if (res.code) {
      return message.error(res.message)
    }
    setProductList(res.data)
  }

  const getParams = () => {
    const params = {}
    if (search.createTime.length === 2) {
      params.start_created_at = Math.floor(search.createTime[0].valueOf() / 1000)
      params.end_created_at = Math.floor(search.createTime[1].valueOf() / 1000)
    }
    if (search.deliverTime.length === 2) {
      params.start_deliver_at = Math.floor(search.deliverTime[0].valueOf() / 1000)
      params.end_deliver_at = Math.floor(search.deliverTime[1].valueOf() / 1000)
    }
    if (search.activeTime.length === 2) {
      params.start_active_at = Math.floor(search.activeTime[0].valueOf() / 1000)
      params.end_active_at = Math.floor(search.activeTime[1].valueOf() / 1000)
    }
    if (search.keyword && search.searchType) {
      params[search.searchType] = search.keyword
    }
    if (search.isp) {
      params.isp = search.isp
    }
    if (search.status) {
      params.status = search.status
    }
    if (search.partner_id) {
      params.partner_id = search.partner_id
    }
    if (search.partner_goods_code && search.partner_goods_code.length) {
      params.partner_goods_code = search.partner_goods_code
    }
    return params
  }

  const getOrderList = async(page = 1) => {
    setIsLoading(true)
    const params = { page, size: pageSize, ...getParams() }
    setCurrentPage(page)
    const { code, message: errMsg, data } = await getList(params)
    setIsLoading(false)
    if (code) {
      message.error(errMsg)
      return false
    }
    setOrderList(data.list)
    setTotalCount(data.total_result)
    setPage(data.page)
  }

  const handleExport = async() => {
    const { code, message: errMsg, data: filename } = await createExport(getParams())
    if (code) {
      message.error(errMsg)
      return false
    }
    setIsExportBtnLoading(true)
    timeId = setInterval(async() => {
      const res = await getExportFile({ filename })
      if (res.code) {
        message.error(res.message)
        clearInterval(timeId)
        setIsExportBtnLoading(false)
        return false
      }
      if (res.data) {
        clearInterval(timeId)
        setIsExportBtnLoading(false)
        window.location.href = res.data
      }
    }, 3000)
  }

  const statusColorMap = {
    1: 'lime',
    3: 'cyan',
    8: '#87d068',
    10: 'gold',
    11: '#f50',
    12: 'red'
  }

  const userSource = name => {
    if (name === '抖音') {
      return (
        <p className="user-source">
          <img src={require('../../../assets/images/douyin.jpg')}/> 抖音
        </p>
      )
    } else if (name === '快手') {
      return (
        <p className="user-source">
          <img src={require('../../../assets/images/kuaishou.jpg')}/> 快手
        </p>
      )
    } else {
      return <p>其他</p>
    }
  }

  const columns = [
    {
      title: '订单信息',
      dataIndex: 'order_no',
      render: (text, record) => (
        <Fragment>
          <p>订单号：{record.order_no}</p>
          <p>新号码：{record.new_phone} {record.guishudi && (<span>({record.guishudi})</span>)}</p>
          <p>下单套餐：{loginUser.role_id === ROLE_CUSTOMER_SERVICE ? '*****' : record.partner_goods_name}</p>
          <p>订单状态：{orderStatusMap[record.status] ? (
            <Tag color={statusColorMap[record.status] || 'blue'}>{orderStatusMap[record.status]}</Tag>
          ) : (
            <span>-</span>
          )}
          </p>
          {record.active_at && (
            <p>激活时间：{moment(record.active_at * 1000).format('YYYY-MM-DD HH:mm:ss')}</p>
          )}
          <p>下单时间：{moment(record.created_at * 1000).format('YYYY-MM-DD HH:mm:ss')}</p>
        </Fragment>
      )
    },
    {
      title: '用户信息',
      render: (text, record) => (
        <Fragment>
          <p>用户姓名：{record.true_name}</p>
          <p>身份证号：{record.idcard}</p>
          <p>电话号码：{record.phone}</p>
          <div>用户来源：{loginUser.role_id === ROLE_CUSTOMER_SERVICE ? '*****' : userSource(record.ad_tp_name)}</div>
        </Fragment>
      )
    },
    {
      title: '地址',
      render: (text, record) => (
        <Fragment>
          <p>省份：{record.province}</p>
          <p>城市：{record.city}</p>
          <p>地区：{record.area}</p>
          <p>地址：{record.address}</p>
        </Fragment>
      )
    },
    {
      title: '快递信息',
      render: (text, record) => (
        <Fragment>
          <p>发货时间：{(record.deliver_at ? (
            <span>{moment(record.deliver_at * 1000).format('YYYY-MM-DD HH:mm:ss')}</span>) : '-')}</p>
          <p>快递公司：{record.express}</p>
          <p>快递单号：{record.express_no}</p>
        </Fragment>
      )
    },
    {
      title: '操作',
      align: 'center',
      allowRoles: [ROLE_ADMIN],
      render: (text, record) => (
        <Fragment>
          <Button
            type="primary"
            size="small"
            style={{ marginRight: '10px' }}
            onClick={() => {
              setEditRow(record)
              setIsShowEdit(true)
            }}
          >
            编辑
          </Button>
          <Button size="small" onClick={() => {
            setCurrentOrderNo(record.order_no)
            setIsShowOrderDetail(true)
          }}>详情</Button>
        </Fragment>
      )
    }
  ]

  const beforeSearchInput = (
    <Select
      style={{ width: '100px' }}
      placeholder="搜索类型"
      onChange={val => setSearch({ ...search, searchType: val })}
      value={search.searchType}
    >
      <Select.Option value="order_no">订单号</Select.Option>
      <Select.Option value="phone">手机号</Select.Option>
      <Select.Option value="new_phone">新号码</Select.Option>
      <Select.Option value="true_name">姓名</Select.Option>
      <Select.Option value="idcard">身份证号</Select.Option>
    </Select>
  )

  return (
    <div className="order-list">
      <div className="search">
        <div className="search--block" style={{ width: '300px' }}>
          <Input
            addonBefore={beforeSearchInput}
            placeholder="请输入搜索内容"
            onChange={e => setSearch({ ...search, keyword: e.target.value })}
          />
        </div>
        <div className="search--block" style={{ width: '350px' }}>
          <DatePicker.RangePicker
            showTime={true}
            locale={locale}
            placeholder={['起始日期', '结束日期']}
            onChange={val => setSearch({ ...search, createTime: val })}
          />
        </div>
        <div className="search--block" style={{ width: '350px' }}>
          <DatePicker.RangePicker
            showTime={true}
            locale={locale}
            onChange={val => setSearch({ ...search, deliverTime: val })}
            placeholder={['发货起始日期', '发货结束日期']}
          />
        </div>
        <div className="search--block" style={{ width: '350px' }}>
          <DatePicker.RangePicker
            showTime={true}
            locale={locale}
            onChange={val => setSearch({ ...search, activeTime: val })}
            placeholder={['激活起始日期', '激活结束日期']}
          />
        </div>
        <div className="search--block" style={{ width: '170px' }}>
          <Select
            placeholder="选择运营商"
            style={{ width: '100%' }}
            allowClear={true}
            onChange={val => setSearch({ ...search, isp: val })}
          >
            {Object.keys(ENUMS.ISP).map(item => (
              <Select.Option key={item} value={Number(item)} label={ENUMS.ISP[item]}>
                {ENUMS.ISP[item]}
              </Select.Option>
            ))}
          </Select>
        </div>
        {loginUser.role_id !== ROLE_AGENT && loginUser.role_id !== ROLE_CUSTOMER_SERVICE && (
          <div className="search--block" style={{ width: '200px' }}>
            <Select
              placeholder="选择渠道"
              style={{ width: '100%' }}
              allowClear={true}
              onChange={val => setSearch({ ...search, partner_id: val })}
            >
              {packageList.map(item => (
                <Select.Option key={item.id} value={item.id} label={item.name}>
                  {item.name}
                </Select.Option>
              ))}
            </Select>
          </div>
        )}
        {loginUser.role_id !== ROLE_CUSTOMER_SERVICE && (
          <div className="search--block" style={{ width: '300px' }}>
            <Select
              placeholder="选择产品"
              style={{ width: '100%' }}
              allowClear={true}
              value={search.partner_goods_code}
              onChange={val => setSearch({ ...search, partner_goods_code: val })}
            >
              {productList.map(item => (
                <Select.Option key={item.id} value={item.code} label={item.name}>
                  {item.name}
                </Select.Option>
              ))}
            </Select>
          </div>
        )}
        {isAll && (
          <div className="search--block" style={{ width: '170px' }}>
            <Select
              placeholder="选择订单状态"
              style={{ width: '100%' }}
              allowClear={true}
              onChange={val => setSearch({ ...search, status: val })}
            >
              {Object.keys(orderStatusMap).map(item => (
                <Select.Option key={item} value={Number(item)} label={ENUMS.ISP[item]}>
                  {orderStatusMap[item]}
                </Select.Option>
              ))}
            </Select>
          </div>
        )}
        <div>
          <Button type="primary" onClick={() => getOrderList()}>搜索</Button>
          {isAll && loginUser.role_id !== ROLE_CUSTOMER_SERVICE && (<Button type="primary" onClick={handleExport} loading={isExportBtnLoading}>导出</Button>)}
        </div>
      </div>
      <div className="menu">
        <Button
          type="primary"
          onClick={() => setIsShowSetStatus(true)}
          disabled={selectedRowKeys.length === 0}
        >
          设置状态
        </Button>
      </div>
      <Table
        rowKey={row => row.order_no}
        loading={isLoading}
        columns={columns.filter(column => (!column.allowRoles || column.allowRoles.indexOf(loginUser.role_id) > -1))}
        dataSource={orderList}
        onChange={page => getOrderList(page.current)}
        rowSelection={{
          selectedRowKeys,
          onChange: keys => {
            setSelectRowKeys(keys)
          }
        }}
        pagination={{
          defaultCurrent: page,
          current: currentPage,
          total: totalCount,
          pageSize,
          showTotal: total => `共 ${total} 条`
        }}
      />
      {isShowEdit && (
        <EditOrder
          visible={isShowEdit}
          order={editRow}
          close={() => {
            setIsShowEdit(false)
            getOrderList()
          }}
        />
      )}
      {isShowOrderDetail && (
        <OrderDetail visible={isShowOrderDetail} orderNo={currentOrderNo} close={() => setIsShowOrderDetail(false)}/>
      )}
      {isShowSetStatus && (
        <SetOrderStatus
          visible={isShowSetStatus}
          order={selectedRowKeys}
          close={() => {
            setIsShowSetStatus(false)
            getOrderList()
          }}
        />
      )}
    </div>
  )
}

export default connect(state => ({
  orderStatusMap: state.getIn(['order', 'orderStatusMap']),
  currentPage: state.getIn(['order', 'currentPage']),
  loginUser: state.getIn(['common', 'loginUser'])
}), dispatch => ({
  setCurrentPage(value) {
    dispatch(actionCreators.setCurrentPage(value))
  }
}))(withRouter(OrderList))
